package com.basin.auth.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.basin.auth.common.enums.PlatformEnum;
import com.basin.auth.common.form.SignUpForm;
import com.basin.auth.core.component.BasinSysRegister;
import com.basin.auth.core.context.LoginContext;
import com.basin.common.core.response.Resp;
import com.basin.common.satoken.annotation.IgnoreGlobalAuth;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Locale;

/**
 * @author: Sam ZHONG | sammy1997@aliyun.com
 */
@RestController
@RequiredArgsConstructor
@Slf4j
@RequestMapping("/")
public class AuthController {
    private final LoginContext loginContext;
    private final BasinSysRegister basinSysRegister;

    @PostMapping("/sign-in")
    public Resp<String> signIn(@RequestParam(name = "platform", defaultValue = "admin") String platform,
                               @RequestParam(name = "loginType", defaultValue = "1") String loginType,
                               @RequestBody Object body) {
        PlatformEnum platformEnum = PlatformEnum.valueOf(platform.toUpperCase(Locale.ROOT));
        String token = loginContext.doLogin(platformEnum, loginType, body);
        return Resp.success(token);
    }

    @PostMapping("/sign-up")
    public Resp<Boolean> signUp(@RequestBody @Validated SignUpForm signUpForm) {
        boolean register = this.basinSysRegister.register(signUpForm);
        return register ? Resp.success("注册成功", true) : Resp.fail("注册失败");
    }

    @GetMapping("/test-login")
    @IgnoreGlobalAuth
    public Resp<String> testLogin() {
        StpUtil.login("test_admin");
        return Resp.success(StpUtil.getTokenValue());
    }
}
